﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using CPPEI.ETL.Domain.Entities;
using CPPEI.ETL.Domain.Services;
using CPPEI.ETL.Infrastructure.Excel;
using CPPEI.ETL.Infrastructure.OpenXml;

namespace CPPEI.ETL.Domain.MessageAlert
{
    public class EmailAlert
    {
        XmlHelper _xmlhelper = new XmlHelper(System.Configuration.ConfigurationManager.AppSettings["SendEmailConfig"]);
        public bool SendEmail(EtlDbContext dbContext, string taskName, DateTime errorDate, string runMode, string error)
        {
            var title = _xmlhelper.GetValue("Title").Replace("{{TaskName}}", taskName).Replace("{{ErrorTime}}", errorDate.ToString("yyyyMMdd HH:mm:ss")).Replace("{{RunModel}}", runMode);
            var content = _xmlhelper.GetValue("Content").Replace("{{TaskName}}", taskName).Replace("{{ErrorTime}}", errorDate.ToString("yyyyMMdd HH:mm:ss")).Replace("{{RunModel}}", runMode).Replace("{{ErrorContent}}", error);

            //发送邮件通知
            List<string> emailList = dbContext.Set<Entities.Maintainer>().Select(p => p.Email).Distinct().ToList();
            if (emailList.Any())
            {
                var state = CPPEI.ETL.Infrastructure.Email.EmailHelper.SendEmail(Configs.EMail_SmtpServer,
                      Configs.EMail_Account,
                      Configs.EMail_Password,
                      emailList, title,
                      content);

                foreach (var item in emailList)
                {
                    dbContext.Set<EMessageAlertRecord>().Add(new EMessageAlertRecord()
                    {
                        Id = Guid.NewGuid(),
                        AlertType = (int)MessageAlertRecordAlertType.Email,
                        Address = item,
                        Content = content,
                        Title = title,
                        CreatedTime = DateTime.Now,
                        Description = "",
                        IsSuccess = state ? (int)MessageAlertRecordIsSuccess.Success : (int)MessageAlertRecordIsSuccess.Fail
                    });
                }
                return dbContext.SaveChanges() > 0;
            }
            return true;
        }

    }
}
